package com.voja.mrvica2;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import com.voja.AndroidUtils.Application;
import com.voja.mrvica2.adapter.EntryAdapter;
import com.voja.mrvica2.request.PostRequest;
import com.voja.mrvica2.rss.RSS;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

public class Share extends Activity {
    
    Intent    intent;
    Bundle    extras;
    Uri       uri;
    Resources res;
    
    ProgressBar  throbber;
    LinearLayout form;
    ArrayList<Entry> groups = new ArrayList<Entry>();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        intent = getIntent();
        extras = intent.getExtras();
        res    = getResources();
        
        Application.setContext(this);
        handleAction();
    }
    
    private void handleAction() {
        String action = intent.getAction();
        
        // application started from share button
        if (action.equals(Intent.ACTION_SEND)) {
            showShare();
            
        // application started separately
        } else {
            showMain();
        }
    }
    
    public void showShare() {
        setContentView(R.layout.share_form);
        
        throbber = (ProgressBar)findViewById(R.id.throbber);
        form     = (LinearLayout)findViewById(R.id.form);
        
        String server = res.getString(R.string.SERVER);
        String action = res.getString(R.string.ACTION_CATEGORIES);
        
        new RSS(this, server + action, "beforeLoadCategories", "afterLoadCategories");
    }
    
    public void beforeLoadCategories() {
    	throbber.setVisibility(View.VISIBLE);
    	form.setVisibility(View.INVISIBLE);
    }
    
    public void afterLoadCategories(ArrayList<Entry> categories) {
    	groups = categories;
    	
    	throbber.setVisibility(View.GONE);
    	form.setVisibility(View.VISIBLE);
    	
    	// populate Group Spinner
    	Spinner selGroups = (Spinner)findViewById(R.id.selProductGroup);
    	ArrayList<String> spinnerGroups = new ArrayList<String>();
    	spinnerGroups.add(res.getString(R.string.newGroup));
    	for (Entry c : groups) {
    		spinnerGroups.add(c.getTitle());
    	}
    	ArrayAdapter<Entry> adapter = new ArrayAdapter(this, R.layout.share_spinner_item, spinnerGroups);
    	selGroups.setAdapter(adapter);
    	
    	// toggle New Group textbox
    	final EditText etNewGroup = (EditText)findViewById(R.id.etNewGroup);
    	selGroups.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> spinner, View view, int pos, long id) {
				String selectedGroup = (String)spinner.getAdapter().getItem(pos);
				if (selectedGroup == res.getString(R.string.newGroup)) {
					etNewGroup.setVisibility(View.VISIBLE);
				} else {
					etNewGroup.setVisibility(View.GONE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
					
			}
		});
    	
    	// populate Image View
    	uri = (Uri)extras.getParcelable(Intent.EXTRA_STREAM);
        if (uri != null) {
            ImageView photo = (ImageView)findViewById(R.id.photoPreview);
            photo.setImageURI(uri);
        }
    }
    
    public void showMain() {
        Application.alert("Activity cannot be started manually.");
    }
    
    public void close(View v) {
        finish();
    }
    
    public void send(View v) {
        if (uri != null) {
            Resources res   = getResources();
            String endpoint = String.format("%s/%s",
                                    res.getString(R.string.SERVER),
                                    res.getString(R.string.ACTION_SHARE)
                              ) ;
            
            
            String path = getRealPath();
            File file = new File(path);
            if (file.exists()) {
                EditText name       = (EditText)findViewById(R.id.name);
                EditText etNewGroup = (EditText)findViewById(R.id.etNewGroup);
                Spinner  selGroups  = (Spinner)findViewById(R.id.selProductGroup);
                
                int    groupId = 0;
                String groupName = etNewGroup.getText().toString();
                int pos = selGroups.getSelectedItemPosition();
                if (pos > 0) {
                	groupId   = groups.get(pos-1).getId();
                	groupName = groups.get(pos-1).getTitle();
                }
                
                if (name.getText().length() > 0 && groupName.length()>0) {
	                HashMap<String, String> data = new HashMap<String, String>();
	                data.put("name",      name.getText().toString());
	                data.put("groupId",   String.valueOf(groupId));
	                data.put("groupName", groupName);
	                PostRequest request = new PostRequest(this, endpoint, data, file);
	                
	                form.setVisibility(View.INVISIBLE);
	                throbber.setVisibility(View.VISIBLE);
	                request.execute();
                } else {
                	Application.alert(res.getString(R.string.allFieldsRequired));
                }
            } else {
                Application.alert("File at " + uri.getPath() + " doesn't exist.");
            }
        }
    }
    
    public void postResponse(HttpResponse response) {
        form.setVisibility(View.VISIBLE);
        throbber.setVisibility(View.GONE);
        if (response != null) {
            String message = "";
            for (Header header : response.getAllHeaders()) {
                message = message + header.getName() + ": " + header.getValue() + "\n";
            }
            
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String line;
                while ((line = reader.readLine()) != null) {
                    message += "\n" + line;
                }
            } catch (Exception e) {
                message += "\n\n- error getting body:\n" + e.getMessage();
            }
            
            Application.alert(message);
        } else {
            Application.alert("Request failed.");
        }
    }
    
    private byte[] readImageFromUri(Uri uri) throws IOException {
        InputStream           stream     = getContentResolver().openInputStream(uri);
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int                   bufferSize = 1024;
        byte[]                buffer     = new byte[bufferSize];
        
        int len = 0;
        while ((len = stream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        
        return byteBuffer.toByteArray();
    }
    
    private String getRealPath() {
        String path = null;
        if (uri != null) {
            String column = MediaStore.Images.Media.DATA;
            Cursor c = getContentResolver().query(
                uri,
                new String[] {column},
                null,
                null,
                null );
            if (c.moveToFirst()) {
                int index = c.getColumnIndexOrThrow(column);
                path = c.getString(index);
            }
        }
        
        return path;
    }

}
